import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wcj
 * @Date 2021/6/17 16:02
 * @Version 1.0
 */
public class ExchangerTest {

    private static Exchanger<String> ex = new Exchanger<>();

    private static ExecutorService executorService = Executors.newFixedThreadPool(2);

    /**
     * Exchanger：用于两个线程在同步点进行数据交换，常用于遗传算法；也可以用于数据的校验
     *
     * @param args
     */
    public static void main(String[] args) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String A = "银行流水A";
                    ex.exchange(A);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String B = "银行流水B";
                    String A = ex.exchange("B");
                    System.out.println("A和B数据是否一致:" + A.equals(B) + ",A录入的是:" + A + ",B录入的是:" + B);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.shutdown();
    }
}
